import { IAMapPio, PluginObject } from '../type';
import { computed, ref, watch } from 'vue';

export default (plugin: { value?: PluginObject }) => {
  const searchVal = ref<string>();
  const searchOption = ref<
    {
      label: string;
      value: any;
    }[]
  >([]);
  let data: ReturnType<PluginObject['searchPlaces']>;

  const titleDiv = document.createElement('div')

  const getSearchOption = async () => {
    searchOption.value = [];
    if (!searchVal.value || !plugin.value) return;
    try {
      
      data = await plugin.value.searchPlaces({
        keywords: searchVal.value,
        city: '500',
      },titleDiv);
      if (data && data.pois && data.pois.length) {
        searchOption.value = data.pois.map((i) => ({
          label: i.name,
          value: i.id,
        }));
      }
    } catch (error) {
      console.log(error);
    }
  };
  const doSelect = (value: string) => {
    console.log(value);
    if (!data || !data.pois ||!data.pois.length) return
    try {
        const poi = data.pois.find(i => i.id === value)
        if (poi) {
            titleDiv.innerHTML = poi.name
            data.flyToPoi(poi,{duration:0.5})
        }
    } catch (error) {
        console.log(error)
    }
  };
  watch(() => searchVal.value, getSearchOption);
  return {
    searchVal,
    searchOption,
    doSelect,
  };
};
